import React, { memo, useCallback } from 'react';
import { useSelector, shallowEqual, useDispatch } from 'react-redux';
import classNames from 'classnames';

import { formatMinuteSecond } from '@/utils/format-utils';

import { PlayListWrapper } from './style';

import { changePlayListAction, changeCurrentSongIndexAction } from "../../../store/actionCreators";

export default memo(function CJXPlayList() {
    const { playList, currentSongIndex, currentSong } = useSelector(state => ({
        playList: state.getIn(["player", "playList"]),
        currentSongIndex: state.getIn(["player", "currentSongIndex"]),
        currentSong: state.getIn(["player", "currentSong"]),
    }), shallowEqual);

    const dispatch = useDispatch();

    const playListDelSong = useCallback((id) => {
        const list = [...playList];
        const index = list.findIndex(ele => ele.id === id);
        list.splice(index, 1);
        const currentPlayIndex = list.findIndex(ele => ele.id === currentSong.id);
        dispatch(changeCurrentSongIndexAction(currentPlayIndex));
        dispatch(changePlayListAction(list))

    }, [dispatch, playList, currentSong]);

    return (
        <PlayListWrapper>
            {
                playList.map((item, index) => {
                    return (
                        <div key={item.id}
                            className={classNames("play-item", { "active": currentSongIndex === index })}>
                            <div className="left">
                                <span>{item.name}</span>
                                <div className="left_2">
                                    <div className="icon_box" onClick={e => playListDelSong(item.id)}><i></i></div>
                                </div>
                            </div>
                            <div className="right">
                                <span className="singer">{item.ar[0].name}</span>
                                <span className="duration">{formatMinuteSecond(item.dt)}</span>
                                <span className="sprite_playlist link"></span>
                            </div>
                        </div>
                    )
                })
            }
        </PlayListWrapper>
    )
})
